package br.com.pheat.servlets;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import br.com.pheat.dao.UsuarioDAO;

public class UsuarioValidarServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
       
    public UsuarioValidarServlet() {
        super();
    }

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		tratarRequisicao(request, response);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		tratarRequisicao(request, response);
	}
	
	protected void tratarRequisicao(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		String login = request.getParameter("login");
		String mensagem = null;
		String pagina = "consulta.jsp";

		try{
			if(login.length() > 20)
				mensagem = "loginGrande";
			else if(UsuarioDAO.existeLogin(login))
				mensagem = "loginIndisponivel";
			else
				mensagem = "loginDisponivel";
		}
		catch(SQLException e){
			pagina = "erro.jsp";
		}catch(Exception e){
			pagina = "erro.jsp";
		}

		request.setAttribute("m", mensagem);
		RequestDispatcher dispatcher = request.getRequestDispatcher(pagina);
		dispatcher.forward(request, response);
	}
}